"use client";

import { useEffect } from 'react';

export function TableOfContents({ content }: { content: string }) {
  const headings = content.match(/^#{1,6}\s+.+$/gm) || [];

  useEffect(() => {
    if (typeof window !== 'undefined') {
      document.documentElement.style.scrollBehavior = 'smooth';
    }
  }, []);

  return (
    <div className="sticky top-24 p-6 bg-white/5 rounded-xl border border-white/10 backdrop-blur-sm">
      <h4 className="text-lg font-semibold mb-4">目录</h4>
      <nav className="space-y-2">
        {headings.map((heading, index) => {
          const matchResult = heading.match(/^#+/);
          const level = matchResult ? matchResult[0].length : 1;
          const title = heading.replace(/^#+\s*/, '').trim();
          const id = title
            .toLowerCase()
            .trim()
            .replace(/\s+/g, '-')
            .replace(/[^\w\u4e00-\u9fa5-]/g, '')
            .replace(/^-+|-+$/g, '');
          return (
            <a
              key={index}
              href={`#${id}`}
              className={`block text-white/60 hover:text-white transition-colors ${level > 1 ? 'pl-' + (level * 2) : ''}`}
            >
              {title}
            </a>
          );
        })}
      </nav>
    </div>
  );
}